package fr.inserm.umr915.vcfserver.xml;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLStreamException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public abstract class XsdSerializer
	{
	public final static String XSD=XMLConstants.W3C_XML_SCHEMA_NS_URI;
	public final static String JXB="http://java.sun.com/xml/ns/jaxb";
	public Element createHeader(Document dom)
		{
		Element root=dom.createElementNS(XSD, "xsd:schema");
		root.setAttributeNS(JXB, "jxb:version","2.0");
		return root;
		}
	
	
	public abstract void createBody(Element root) throws XMLStreamException;
	
	public Document create()
		{
		try {
			DocumentBuilderFactory f=DocumentBuilderFactory.newInstance();
			f.setIgnoringComments(false);
			f.setNamespaceAware(true);
			DocumentBuilder b=f.newDocumentBuilder();
			Document dom=b.newDocument();
			Element root=createHeader(dom);
			createBody(root);
			return dom;
			}
		catch (Exception e)
			{
			throw new RuntimeException(e);
			}
		}
	
	protected Element intElement(Element root,String localName)
		{
		return element(root,localName,"int");
		}
	
	protected Element element(Element root,String localName)
		{
		return element(root,localName,"string");
		}
	
	protected Element element(Element root ,String localName,String type)
		{
		return element(root,localName,type,1,1);
		}
	
	protected Element element(Element root,String localName,String type,int minOccurs,Integer maxOccurs)
		{
		Element e=root.getOwnerDocument().createElementNS(XSD, "xsd:element");
		
		e.setAttribute("name",localName);
		e.setAttribute("type","xsd:"+type);
		e.setAttribute("minOccurs",String.valueOf(minOccurs));
		e.setAttribute("maxOccurs",maxOccurs==null?"unbounded":String.valueOf(maxOccurs));
		return e;
		}
	
	}
